<template>
  <view class="messages-container">
    <!-- 选项卡 -->
    <view class="tab-bar-top">
      <text :class="{ 'active-tab': currentTab === 'todo' }" @click="currentTab = 'todo'">待质检</text>
      <text :class="{ 'active-tab': currentTab === 'done' }" @click="currentTab = 'done'">已质检</text>
    </view>

    <!-- 待办列表 -->
    <view v-if="currentTab === 'todo'" class="list-container">
      <!-- 原料质检模块 -->
      <view class="module-title">原料质检</view>
      <view v-for="item in materialTodoList" :key="item.id" class="message-item">
        <view class="message-title">
          <text>{{ item.materialName }} - 批次号: {{ item.lotNumber }}</text>
          <text>{{ item.typeName }} - 质检员: {{ item.nickName }}</text>
        </view>
        <view class="message-actions">
          <button 
            class="inspect-button" 
            :class="{ 'confirm-button': item.result === 2, 'inspect-button': item.result === 3 }" 
            @click="viewDetail(item)"
            :disabled="item.result === 0"
          >
            {{ item.result === 2 ? '待确认' : '待质检' }}
          </button>
        </view>
      </view>

      <!-- 产品质检模块 -->
      <view class="module-title">产品质检</view>
      <view v-for="proitem in productTodoList" :key="proitem.id" class="message-item">
        <view class="message-title">
          <text>{{ proitem.materialName }} - 批次号: {{ proitem.lotNumber }}</text>
          <text>{{ proitem.productTypeName }} - 质检员: {{ proitem.userName }}</text>
        </view>
        <view class="message-actions">
          <button 
            class="inspect-button" 
            :class="{ 'confirm-button': proitem.result === '2', 'inspect-button': proitem.result === '3' }" 
            @click="viewProductDetail(proitem)"
            :disabled="proitem.result === '0'"
          >
            {{ proitem.result === '2' ? '待确认' : '待质检' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 已办列表 -->
    <view v-if="currentTab === 'done'" class="list-container">
      <!-- 原料质检模块 -->
      <view class="module-title">原料质检</view>
      <view v-for="item in materialDoneList" :key="item.id" class="message-item">
        <view class="message-title">
          <text>{{ item.materialName }} - 批次号: {{ item.lotNumber }}</text>
          <text>{{ item.typeName }} - 质检员: {{ item.nickName }}</text>
        </view>
        <view class="message-actions">
          <button class="qualified-button" @click="viewDetail(item)" :disabled="item.result === 0">
            合格
          </button>
        </view>
      </view>

      <!-- 产品质检模块 -->
      <view class="module-title">产品质检</view>
      <view v-for="proitem in productDoneList" :key="proitem.id" class="message-item">
        <view class="message-title">
          <text>{{ proitem.materialName }} - 批次号: {{ proitem.lotNumber }}</text>
          <text>{{ proitem.productTypeName }} - 质检员: {{ proitem.userName }}</text>
        </view>
        <view class="message-actions">
          <button class="qualified-button" @click="viewProductDetail(proitem)" :disabled="proitem.result === '0'">
            合格
          </button>
        </view>
      </view>

      <view v-if="materialDoneList.length === 0 && productDoneList.length === 0" class="no-data">
        <text>暂无已质检数据</text>
      </view>
    </view>

    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view class="tab-item" :class="{ active: currentTab === 'home' }" @click="switchTab('/pages/index/index', 'home')">
        <icon type="home" size="24" :color="currentTab === 'home' ? '#4080FF' : '#999999'"></icon>
        <text class="tab-text">首页</text>
      </view>
      <view class="tab-item active">
        <icon type="chat" size="24" color="#4080FF"></icon>
        <text class="tab-text">消息</text>
      </view>
      <view class="tab-item" :class="{ active: currentTab === 'profile' }" @click="switchTab('/pages/mine/index', 'profile')">
        <icon type="person" size="24" :color="currentTab === 'profile' ? '#4080FF' : '#999999'"></icon>
        <text class="tab-text">我的</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentTab: 'todo',
      materialTodoList: [],
      productTodoList: [],
      materialDoneList: [],
      productDoneList: []
    };
  },
  created() {
    this.fetchMessages();
    this.fetchProMessages();
  },
  methods: {
    fetchMessages() {
      const storedInfo = uni.getStorageSync('userIdInfo');
      if (storedInfo && storedInfo.userId) {
        const userId = storedInfo.userId;
        uni.request({
          url: `http://127.0.0.1:1101/MesMaterialQualityInspectionDetail/findDetailById?userId=${userId}`,
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200 && Array.isArray(res.data.data)) {
              this.materialTodoList = res.data.data.filter(item => item.result === 2 || item.result === 3);
              this.materialDoneList = res.data.data.filter(item => item.result === 0);
            } else {
              console.error('Unexpected data format:', res.data);
            }
          },
          fail: (err) => console.error('Error fetching data:', err)
        });
      } else {
        uni.showToast({ title: '用户未登录', icon: 'none' });
      }
    },
    fetchProMessages() {
      const storedInfo = uni.getStorageSync('userIdInfo');
      if (storedInfo && storedInfo.userId) {
        const userId = storedInfo.userId;
        uni.request({
          url: `http://127.0.0.1:1005/detail/list?userId=${userId}`,
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200 && Array.isArray(res.data.data)) {
              // 确保每个项目都有 productTypeName 和 userName 字段
              const filteredData = res.data.data.filter(proitem => proitem.result === '2' || proitem.result === '3');
              if (filteredData.length > 0) {
                this.productTodoList = filteredData;
              }
              // 合并 productDoneList 时，确保不重复添加
              const newDoneItems = res.data.data.filter(proitem => proitem.result === '0');
              if (newDoneItems.length > 0) {
                this.productDoneList = [
                  ...this.productDoneList,
                  ...newDoneItems.filter(proitem => !this.productDoneList.some(doneItem => doneItem.id === proitem.id))
                ];
              }
            }
          },
        });
      }
    },
    viewDetail(item) {
      if (item.result === 3) {
        // result === '3' 时，跳转到 messageDetail 页面
        uni.navigateTo({
          url: `/pages/messageDetail/index?id=${item.id}&title=${encodeURIComponent(item.materialName)}`
        });
      } else if (item.result !== 0) {
        // 其他情况执行确认逻辑
        let message = item.result === 2 ? "确定要确认该明细吗？" : "是否对原料进行质检？";
        uni.showModal({
          title: "确认操作",
          content: message,
          success: (res) => {
            if (res.confirm) {
              uni.request({
                url: `http://127.0.0.1:1005/mesMaterialQualityDetail/setQuality/${item.id}`,
                method: "GET",
                success: (response) => {
                  if (response.data.code === 200) {
                    uni.showToast({ title: "操作成功", icon: "success" });
                    this.fetchMessages();
                  } else {
                    uni.showToast({ title: "操作失败", icon: "none" });
                  }
                },
                fail: () => {
                  uni.showToast({ title: "请求失败", icon: "none" });
                }
              });
            }
          }
        });
      }
    },
    viewProductDetail(proitem) {
      if (proitem.result === '3') {
        // result === '3' 时，跳转到 messageDetail 页面
        uni.navigateTo({
          url: `/pages/messageProDetail/index?id=${proitem.id}&title=${encodeURIComponent(proitem.materialName)}`
        });
      } else if (proitem.result !== '0') {
        // 其他情况执行确认逻辑
        let message = proitem.result === '2' ? "确定要确认该明细吗？" : "是否对产品进行质检？";
        uni.showModal({
          title: "确认操作",
          content: message,
          success: (res) => {
            if (res.confirm) {
              uni.request({
                url: `http://127.0.0.1:1005/detail/setQuality/${proitem.id}`, // 假设产品质检的接口是 setProductQuality
                method: "GET",
                success: (response) => {
                  if (response.data.code === 200) {
                    uni.showToast({ title: "操作成功", icon: "success" });
                    this.fetchProMessages();
                  } else {
                    uni.showToast({ title: "操作失败", icon: "none" });
                  }
                },
                fail: () => {
                  uni.showToast({ title: "请求失败", icon: "none" });
                }
              });
            }
          }
        });
      }
    },
    switchTab(url, tab) {
      this.currentTab = tab;
      uni.switchTab({ url });
    }
  }
};
</script>

<style scoped>
.messages-container {
  padding: 20rpx;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
  padding-bottom: 120rpx; /* 确保底部导航栏不遮挡内容 */
}

/* 顶部切换栏 */
.tab-bar-top {
  display: flex;
  justify-content: space-around;
  background-color: #ffffff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  border-bottom: 1px solid #eeeeee;
}

.tab-bar-top text {
  font-size: 32rpx;
  padding: 10rpx 20rpx;
  cursor: pointer;
}

.active-tab {
  font-weight: bold;
  color: #007aff;
  border-bottom: 4rpx solid #007aff;
}

/* 消息列表 */
.list-container {
  margin-bottom: 20rpx;
}

.module-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding: 10rpx 0;
  border-bottom: 1px solid #eeeeee;
}

.message-item {
  background-color: #ffffff;
  padding: 30rpx;
  margin-bottom: 10rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  position: relative;
}

.message-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.message-title text {
  display: block;
}

.message-actions {
  position: absolute;
  bottom: 30rpx;
  right: 30rpx;
}

.inspect-button {
  background-color: #4080FF;
  color: #ffffff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
  cursor: pointer;
}

.inspect-button:active {
  background-color: #3366cc;
}

.confirm-button {
  background-color: #FFA500; /* 橙色 */
  color: #ffffff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
  cursor: pointer;
}

.confirm-button:active {
  background-color: #FF8C00; /* 深橙色 */
}

.qualified-button {
  background-color: #28a745; /* 绿色 */
  color: #ffffff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  cursor: pointer;
}

.qualified-button:active {
  background-color: #218838; /* 深绿色 */
}

/* 底部导航栏 */
.tab-bar {
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-top: 1px solid #eeeeee;
  flex-shrink: 0;
  box-shadow: 0 -4rpx 8rpx rgba(0, 0, 0, 0.1);
  position: fixed;
  bottom: 0;
  width: 100%;
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: color 0.2s ease;
}

.tab-text {
  font-size: 12px;
  color: #999999;
  margin-top: 8rpx;
}

.active .tab-text {
  color: #4080ff;
}
</style>
